// src/utils/request.js
import axios from 'axios'
import { Message } from 'element-ui'

// 创建axios实例
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API || 'http://localhost:9999',
    timeout: 10000,
    withCredentials: true // 重要：允许携带cookie
})

// request拦截器
service.interceptors.request.use(
    config => {
        // 确保携带cookie
        config.withCredentials = true
        return config
    },
    error => {
        console.error('请求错误:', error)
        return Promise.reject(error)
    }
)

// response拦截器
service.interceptors.response.use(
    response => {
        const res = response.data

        if (res.success !== undefined) {
            return res
        } else {
            return Promise.reject(new Error('响应格式错误'))
        }
    },
    error => {
        console.error('响应错误:', error)

        if (error.response) {
            switch (error.response.status) {
                case 401:
                    Message({
                        message: '未授权，请重新登录',
                        type: 'error'
                    })
                    break
                case 403:
                    Message({
                        message: '拒绝访问',
                        type: 'error'
                    })
                    break
                case 500:
                    Message({
                        message: '服务器内部错误',
                        type: 'error'
                    })
                    break
                default:
                    Message({
                        message: error.response.data.message || '请求失败',
                        type: 'error'
                    })
            }
        } else {
            Message({
                message: error.message || '网络错误',
                type: 'error'
            })
        }

        return Promise.reject(error)
    }
)

export default service
